import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LianBao
 * Date: 2024-09-02
 * Time: 13:44
 */

//客户端
public class udpEchoClient {
    DatagramSocket socket = null;

    private String serverIp;//服务器的ip
    private int serverPort;//服务器的端口号

    public udpEchoClient(String serverIp, int serverPort) throws SocketException {
        socket = new DatagramSocket();
        //客户端一般不指定端口号,客户端是主动的一方,不需要让服务器找他.让系统自动分配端口
        //用户的电脑上运行了很多程序,用户可能指定的端口号是和其他程序的端口冲突了
        this.serverIp = serverIp;
        this.serverPort = serverPort;
    }

    public void start() throws IOException {
        System.out.println("启动客户端");
        Scanner scanner = new Scanner(System.in);
        while (true) {
            //1.从控制台读取到用户的输入
            String request = scanner.nextLine();
            //2.构造UDP请求,发送给服务器
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(), request.getBytes().length
                    , InetAddress.getByName(this.serverIp), this.serverPort);//
            //InetAddress.getByName(this.serverIp),这里是把ip包裹一下,转换成所需的二进制格式,
            socket.send(requestPacket);
            //3.从服务器中读取响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(responsePacket);
            //4.把响应打印到看看系统上
            String response = new String(responsePacket.getData(), 0, responsePacket.getLength());
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        udpEchoClient client = new udpEchoClient("127.0.0.1", 9090);
        client.start();
    }
}
